import axios from "axios";
import {useAuthStore} from "@/store/index.js";
import router from "@/router/index.js";
import {routeMeta} from "@/router/routes.js";

const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000,
    headers: {
        "Content-Type": "application/json",
    },
});

// Request interceptor
request.interceptors.request.use(
    (config) => {
        const authStore = useAuthStore();
        if (authStore.isAuthenticated) {
            config.headers.Authorization = `Bearer ${authStore.token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Response interceptor
request.interceptors.response.use(
    (response) => {
        const data = response.data
        const {code, message} = data
        if (code === 1) {
            return data
        }
        // 其他情况统一提示错误信息
        const errorMsg = message || '未知异常，请联系管理员'
        window.$message.error(errorMsg)
        return Promise.reject(errorMsg)
    },
    (error) => {
        console.error(error)
        const status = error.response.status
        // 根据后端全局异常处理返回的 status 做统一拦截
        switch (status) {
            case 400:
                window.$message.warning('请求参数错误')
                break
            case 401:
                window.$message.error('未登录或登录已过期')
                // 跳转登录页
                router.push({name: routeMeta.name.LOGIN})
                break
            case 403:
                window.$message.error('没有权限访问')
                break
            case 404:
                window.$message.error('请求资源不存在')
                break
            case 415:
                window.$message.error('请求媒体类型不支持')
                break
            case 500:
                window.$message.error('服务器内部错误，请联系管理员')
                break
            default:
                window.$message.error('请求错误')
        }
        return Promise.reject(error);
    }
);

export default request;